package cn.youdian.service.impl;

import cn.youdian.core.util.SecurityUtils;
import cn.youdian.data.entity.User;
import cn.youdian.data.mapper.UserMapper;
import cn.youdian.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 用户服务实现类
 *
 * @author K.J
 * @date 2021.05.29 21:25:06
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Long insert(User user) {
        user.setCreateTs(new Date());
        user.setLastTs(new Date());
        user.setLastLoginTs(new Date());
        user.setPassword(SecurityUtils.hmacSHA512(user.getPassword(), user.getSalt()));
        userMapper.insert(user);
        return user.getId();
    }

    @Override
    public void update(User user) {

        user.setPassword(SecurityUtils.hmacSHA512(user.getPassword(), user.getSalt()));
        user.setLastTs(new Date());
        userMapper.updateById(user);
    }

    @Override
    public User queryByUserName(String userName) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery();
        queryWrapper.like(User::getUserName, userName);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public User login(String userName, String password) {

        //获取用户信息
        User user = this.queryByUserName(userName);
        if (user != null) {
            //使用用户输入登录密码与Salt加密后, 再与数据库用户密码比较是否一致
            String nPassword = SecurityUtils.hmacSHA512(password, user.getSalt());
            if (nPassword.equals(user.getPassword())) {
                return user;
            }
        }
        return null;
    }
}
